//
//  TTDetailFilterHeaderView.m
//  TaoTuo
//
//  Created by admin on 2019/8/28.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTDetailFilterHeaderView.h"
#import "TTDetailModel.h"
#import "TTFiltrateView.h"
#import "TTXianhuoModel.h"

#define rowH 30

@interface TTSubFilterView : UIView

@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) TTFiltrateView *filterView;
@property (nonatomic, copy) void(^selectBlock)(NSString *selectString);

@property (nonatomic, strong) NSArray *dataArray;
@property (nonatomic, copy) NSString *title;

@property (nonatomic, assign) BOOL isSelect;    // 是否有选中的


+ (instancetype)filterViewWithFrame:(CGRect)frame title:(NSString *)title datasArray:(NSArray *)datasArray selectBlock:(void(^)(NSString *selectString))selectBlock;

@end

@implementation TTSubFilterView

+ (instancetype)filterViewWithFrame:(CGRect)frame title:(NSString *)title datasArray:(NSArray *)datasArray selectBlock:(void(^)(NSString *))selectBlock
{
    return [[self alloc] initWithFrame:frame title:title datasArray:datasArray selectBlock:selectBlock];
}

- (instancetype)initWithFrame:(CGRect)frame title:(NSString *)title datasArray:(NSArray *)datasArray selectBlock:(void(^)(NSString *))selectBlock
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.title = title;
        self.dataArray = datasArray;
        self.selectBlock = selectBlock;
        
        self.titleLabel.text = self.title;
        
    }
    return self;
}

- (void)setDataArray:(NSArray *)dataArray
{
    _dataArray = dataArray;
    self.filterView.dataArray = self.dataArray;
}

- (UILabel *)titleLabel
{
    if (!_titleLabel) {
        _titleLabel = [UILabel labelWithTitle:self.title color:UIColorHex(333333) fontSize:12];
        _titleLabel.frame = CGRectMake(0, 0, 40, self.height);
        _titleLabel.textAlignment = NSTextAlignmentRight;
        [self addSubview:_titleLabel];
    }
    return _titleLabel;
}

// 单选的
- (TTFiltrateView *)filterView
{
    if (!_filterView) {
        @weakify(self)
        _filterView = [[TTFiltrateView alloc] initWithFrame:CGRectMake(self.titleLabel.right, 0, self.width - self.titleLabel.right, self.height) allowsMultiple:NO selectedArrayBlock:^(NSArray * _Nullable selectedArray) {
            @strongify(self)
            // 取消选中了
            self.isSelect = selectedArray.count > 0;
            if (selectedArray.count == 0) {
                self.filterView.dataArray = self.dataArray;
                if (self.selectBlock) {
                    self.selectBlock(@"");
                }
            } else {
                // 选中了一个
                if (self.selectBlock) {
                    self.selectBlock(selectedArray.firstObject);
                    self.filterView.dataArray = selectedArray;
                    [self.filterView setSelectedFirstItemAndNoBlock];
                }
            }
            
            
        } leftRightSpace:5 cornerRadius:3];
        [self addSubview:_filterView];
    }
    return _filterView;
}

@end



@interface TTDetailFilterHeaderView ()

@property (nonatomic, strong) TTDetailModel *model;

@property (nonatomic, strong) TTSubFilterView *xkFilterView;
@property (nonatomic, strong) TTSubFilterView *scFilterView;
@property (nonatomic, strong) TTSubFilterView *njFilterView;
@property (nonatomic, strong) TTSubFilterView *csFilterView;
@property (nonatomic, strong) TTSubFilterView *zgFilterView;
@property (nonatomic, strong) TTSubFilterView *cpFilterView;
@property (nonatomic, strong) TTSubFilterView *ysFilterView;

@property (nonatomic, strong) NSArray *insertSizeList;
@property (nonatomic, strong) NSArray *handSizeList;
@property (nonatomic, strong) NSArray *braceletSizeList;
@property (nonatomic, strong) NSArray *goldColorList;
@property (nonatomic, strong) NSArray *productGradeList;
@property (nonatomic, strong) NSArray *finishedProductList;
@property (nonatomic, strong) NSArray *productColorList;

@property (nonatomic, copy) CanShowDatasBlock datasBlock;

@property (nonatomic, strong) NSMutableArray *filterViewsArray;     // s视图
@property (nonatomic, strong) NSMutableArray *filterViewDatasArray; // 视图原始数据
@property (nonatomic, strong) NSArray *dataArray;

@end

@implementation TTDetailFilterHeaderView

// 筛选出列表中包含的元素展示出来
- (NSArray *)findContainItemWithField:(NSString *)field sourceArray:(NSArray *)sourceArray fromArray:(NSArray *)fromArray
{
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF in %@.%@", fromArray, field];
    NSArray *result = [sourceArray filteredArrayUsingPredicate:predicate];
    if (result.count == 0) {
        NSMutableArray *arr = [NSMutableArray array];
        for (TTDetailStockListModel *model in fromArray) {
            NSString *str = [model valueForKey:field];
            if (str.length > 0 && ![arr containsObject:str]) {
                [arr addObject:str];
                [arr sortUsingComparator:^NSComparisonResult(NSString *  _Nonnull str1, NSString *  _Nonnull str2) {
                    // 按数字排序
                    return [str1 compare:str2 options:NSNumericSearch];
                }];
            }
        }
        return arr;
    }
    return result;
}

- (instancetype)initWithFrame:(CGRect)frame model:(TTXianhuoModel *)model dataArray:(nonnull NSArray *)dataArray canShowDatas:(nonnull CanShowDatasBlock)showDatas
{
    self = [super initWithFrame:frame];
    if (self) {
        
        int count = 0;
        _insertSizeList = [self findContainItemWithField:@"InsertSize" sourceArray:model.InsertSizeList fromArray:dataArray];
        _handSizeList = [self findContainItemWithField:@"HandSize" sourceArray:model.HandSizeList fromArray:dataArray];
        _braceletSizeList = [self findContainItemWithField:@"BraceletSize" sourceArray:model.BraceletSizeList fromArray:dataArray];
        _goldColorList = [self findContainItemWithField:@"GoldColor" sourceArray:model.GoldColorList fromArray:dataArray];
        _productGradeList = [self findContainItemWithField:@"ProductGradeName" sourceArray:model.ProductGradeList fromArray:dataArray];
        _finishedProductList = [self findContainItemWithField:@"IsFinishedProduct" sourceArray:model.FinishedProductList fromArray:dataArray];
        _productColorList = [self findContainItemWithField:@"ProductColor" sourceArray:model.ProductColorList fromArray:dataArray];
        
        count = _insertSizeList.count > 0 ? count+=1 : count;
        count = _handSizeList.count > 0 ? count+=1 : count;
        count = _braceletSizeList.count > 0 ? count+=1 : count;
        count = _goldColorList.count > 0 ? count+=1 : count;
        count = _productGradeList.count > 0 ? count+=1 : count;
        count = _finishedProductList.count > 0 ? count+=1 : count;
        count = _productColorList.count > 0 ? count+=1 : count;
        
//        count = model.InsertSizeList.count > 0 ? count+=1 : count;
//        count = model.HandSizeList.count > 0 ? count+=1 : count;
//        count = model.BraceletSizeList.count > 0 ? count+=1 : count;
//        count = model.GoldColorList.count > 0 ? count+=1 : count;
//        count = model.ProductGradeList.count > 0 ? count+=1 : count;
//        count = model.FinishedProductList.count > 0 ? count+=1 : count;
//        count = model.ProductColorList.count > 0 ? count+=1 : count;
        
        CGFloat h = count * rowH + 8;
        self.frame = CGRectMake(0, 0, SCREEN_WIDTH, h);
        
        self.model = model;
        self.datasBlock = showDatas;
        self.dataArray = dataArray.copy;
        [self setupSubviews];
        
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    _xkFilterView.frame = CGRectMake(0, 8, self.width, _insertSizeList.count > 0 ? rowH : 0);
    _scFilterView.frame = CGRectMake(0, _xkFilterView.bottom, self.width, _handSizeList.count > 0 ? rowH : 0);
    _njFilterView.frame = CGRectMake(0, _scFilterView.bottom, self.width, _braceletSizeList.count > 0 ? rowH : 0);
    _csFilterView.frame = CGRectMake(0, _njFilterView.bottom, self.width, _goldColorList.count > 0 ? rowH : 0);
    _zgFilterView.frame = CGRectMake(0, _csFilterView.bottom, self.width, _productGradeList.count > 0 ? rowH : 0);
    _cpFilterView.frame = CGRectMake(0, _zgFilterView.bottom, self.width, _finishedProductList.count > 0 ? rowH : 0);
    _ysFilterView.frame = CGRectMake(0, _cpFilterView.bottom, self.width, _productColorList.count > 0 ? rowH : 0);
    
}



- (void)configDic:(NSMutableDictionary *)dic field:(NSString *)fieldString string:(NSString *)string
{
    if (string.length == 0) {
        [dic removeObjectForKey:fieldString];
    } else {
        [dic setObject:string forKey:fieldString];
    }
    
    // 查询语句
    NSString *conditionString = @"";
    for (NSString *key in dic.allKeys) {
        NSString *value = dic[key];
        
        conditionString = [NSString stringWithFormat:@"%@SELF.%@ = '%@' && ", conditionString, key, value];
    }
    
    if (conditionString.length > 4) {
        conditionString = [conditionString substringToIndex:conditionString.length - 4];
    }
    NSLog(@"%@", conditionString);
    
    if (conditionString.length == 0) {
        if (self.datasBlock) {
            self.datasBlock(self.dataArray);
        }
        
        for (int i = 0; i < self.filterViewsArray.count; i++) {
            TTSubFilterView *sfView = self.filterViewsArray[i];
            NSArray *arr = self.filterViewDatasArray[i];
            sfView.dataArray = arr;
        }
        
    } else {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:conditionString];
        NSArray *result = [self.dataArray filteredArrayUsingPredicate:predicate];
        
        if (self.datasBlock) {
            self.datasBlock(result);
        }
        
        NSMutableArray *xkArr = @[].mutableCopy;
        NSMutableArray *scArr = @[].mutableCopy;
        NSMutableArray *njArr = @[].mutableCopy;
        NSMutableArray *csArr = @[].mutableCopy;
        NSMutableArray *zgArr = @[].mutableCopy;
        NSMutableArray *cpArr = @[].mutableCopy;
        NSMutableArray *ysArr = @[].mutableCopy;
        for (TTDetailStockListModel *sModel in result) {
            [self addObjectWithArray:xkArr str:sModel.InsertSize];
            [self addObjectWithArray:scArr str:sModel.HandSize];
            [self addObjectWithArray:njArr str:sModel.BraceletSize];
            [self addObjectWithArray:csArr str:sModel.GoldColor];
            [self addObjectWithArray:zgArr str:sModel.ProductGradeName];
            [self addObjectWithArray:cpArr str:sModel.IsFinishedProduct];
            [self addObjectWithArray:ysArr str:sModel.ProductColor];
        }
        
        // 排序
        [xkArr sortUsingComparator:^NSComparisonResult(NSString * _Nonnull obj1, NSString *  _Nonnull obj2) {
            return [obj1 compare:obj2 options:NSNumericSearch];
        }];
        [scArr sortUsingComparator:^NSComparisonResult(NSString * _Nonnull obj1, NSString *  _Nonnull obj2) {
            return [obj1 compare:obj2 options:NSNumericSearch];
        }];
        [njArr sortUsingComparator:^NSComparisonResult(NSString * _Nonnull obj1, NSString *  _Nonnull obj2) {
            if ([obj1 containsString:@"mm"]) {
                NSRange range1 = [obj1 rangeOfString:@"mm"];
                NSRange range2 = [obj2 rangeOfString:@"mm"];
                CGFloat a1 = [[obj1 substringToIndex:range1.location] floatValue];
                CGFloat a2 = [[obj2 substringToIndex:range2.location] floatValue];
                return a1 > a2;
                
            } else {
                return [obj1 compare:obj2 options:NSNumericSearch];
            }
            
        }];
        
        NSMutableArray *array = [NSMutableArray arrayWithObjects:xkArr, scArr, njArr, csArr, zgArr, cpArr, ysArr, nil];
        
        for (int i = 0; i < self.filterViewsArray.count; i++) {
            TTSubFilterView *sfView = self.filterViewsArray[i];
            NSArray *arr = array[i];
            if (!sfView.isSelect) {
                sfView.dataArray = arr; // 如果没有选中，刷新一下
            }
        }
    }
    
    
    
}

- (void)addObjectWithArray:(NSMutableArray *)array str:(NSString *)str
{
    if (![array containsObject:str] && str.length > 0) {
        [array addObject:str];
    }
}

- (void)setupSubviews
{

    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    _xkFilterView = [TTSubFilterView filterViewWithFrame:CGRectMake(0, 0, self.width, rowH) title:@"镶口:" datasArray:_insertSizeList selectBlock:^(NSString *selectString) {
        
        [self configDic:dic field:@"InsertSize" string:selectString];
        
        
        NSLog(@"--> %@", selectString);
        
    }];
    _xkFilterView.hidden = _insertSizeList.count == 0;
    [self addSubview:_xkFilterView];
    
    _scFilterView = [TTSubFilterView filterViewWithFrame:CGRectMake(0, _xkFilterView.bottom, self.width, rowH) title:@"手寸:" datasArray:_handSizeList selectBlock:^(NSString *selectString) {
        
        [self configDic:dic field:@"HandSize" string:selectString];
        
    }];
    _scFilterView.hidden = _handSizeList.count == 0;
    [self addSubview:_scFilterView];
    
    _njFilterView = [TTSubFilterView filterViewWithFrame:CGRectMake(0, _scFilterView.bottom, self.width, rowH) title:@"内径:" datasArray:_braceletSizeList selectBlock:^(NSString *selectString) {
        
        [self configDic:dic field:@"BraceletSize" string:selectString];
        
    }];
    _njFilterView.hidden = _braceletSizeList.count == 0;
    [self addSubview:_njFilterView];
    
    _csFilterView = [TTSubFilterView filterViewWithFrame:CGRectMake(0, _njFilterView.bottom, self.width, rowH) title:@"成色:" datasArray:_goldColorList selectBlock:^(NSString *selectString) {
        
        
        [self configDic:dic field:@"GoldColor" string:selectString];
        
    }];
    _csFilterView.hidden = _goldColorList.count == 0;
    [self addSubview:_csFilterView];
    
    _zgFilterView = [TTSubFilterView filterViewWithFrame:CGRectMake(0, _scFilterView.bottom, self.width, rowH) title:@"做工:" datasArray:_productGradeList selectBlock:^(NSString *selectString) {
        
        [self configDic:dic field:@"ProductGradeName" string:selectString];
        
    }];
    _zgFilterView.hidden = _productGradeList.count == 0;
    [self addSubview:_zgFilterView];
    
    _cpFilterView = [TTSubFilterView filterViewWithFrame:CGRectMake(0, _zgFilterView.bottom, self.width, rowH) title:@"产品:" datasArray:_finishedProductList selectBlock:^(NSString *selectString) {
        
        [self configDic:dic field:@"IsFinishedProduct" string:selectString];
        
    }];
    _cpFilterView.hidden = _finishedProductList.count == 0;
    [self addSubview:_cpFilterView];
    
    _ysFilterView = [TTSubFilterView filterViewWithFrame:CGRectMake(0, _cpFilterView.bottom, self.width, rowH) title:@"颜色:" datasArray:_productColorList selectBlock:^(NSString *selectString) {
        
        [self configDic:dic field:@"ProductColor" string:selectString];
        
    }];
    _ysFilterView.hidden = _productColorList.count == 0;
    [self addSubview:_ysFilterView];
    
    
    [self.filterViewsArray removeAllObjects];
    [self.filterViewsArray addObject:_xkFilterView];
    [self.filterViewsArray addObject:_scFilterView];
    [self.filterViewsArray addObject:_njFilterView];
    [self.filterViewsArray addObject:_csFilterView];
    [self.filterViewsArray addObject:_zgFilterView];
    [self.filterViewsArray addObject:_cpFilterView];
    [self.filterViewsArray addObject:_ysFilterView];
    
    [self.filterViewDatasArray removeAllObjects];
    [self.filterViewDatasArray addObject:_insertSizeList];
    [self.filterViewDatasArray addObject:_handSizeList];
    [self.filterViewDatasArray addObject:_braceletSizeList];
    [self.filterViewDatasArray addObject:_goldColorList];
    [self.filterViewDatasArray addObject:_productGradeList];
    [self.filterViewDatasArray addObject:_finishedProductList];
    [self.filterViewDatasArray addObject:_productColorList];
    
    
    [self setNeedsLayout];
}

- (NSMutableArray *)filterViewsArray
{
    if (!_filterViewsArray) {
        _filterViewsArray = [NSMutableArray array];
    }
    return _filterViewsArray;
}

- (NSMutableArray *)filterViewDatasArray
{
    if (!_filterViewDatasArray) {
        _filterViewDatasArray = [NSMutableArray array];
    }
    return _filterViewDatasArray;
}

@end
